#!/usr/bin/php5
<?php

function test($fp, $str, $mutex)
{
    for ($i = 1; $i <= 100; ++$i) {
        Mutex::lock($mutex);
        $s = sprintf("%s thread, count = %d\n", $str, $i);
        $l = strlen($s);
        for ($j = 0; $j < $l; ++$j) {
            fwrite($fp, $s[$j]);
        }
        Mutex::unlock($mutex);
    }
}

class kyo extends Thread
{
    private $fp = null;
    private $mutex = null;

    public function __construct($fp, $mutex)
    {
        $this->fp = $fp;
        $this->mutex = $mutex;
    }

    public function run()
    {
        test($this->fp, "child", $this->mutex);
    }
}

function main($argc, & $argv)
{
    $fp = fopen("test_file", "w");
    $mutex = Mutex::create();

    $v = new kyo($fp, $mutex);
    $v->start();

    test($fp, "main", $mutex);

    $v->join();

    Mutex::destroy($mutex);

    fclose($fp);

    return 0;
}

exit(main($argc, $argv));

